import React, {useCallback, useMemo, useRef, useState} from 'react';
import {Button, Drawer, Divider, message, Popconfirm} from 'antd';
import moment from 'moment';
import {useLocation} from 'dva';
import {useMount} from 'ahooks';
import {CustomerTable} from '@/modules/CustomerTable';
import {serviceGetTodoList} from '@/services/todo';
import {serviceDeleteTodo} from "@/services/todo";
import TableQueryForm from './queryForm';
import ToDoDetail from '../detail';
import ToDoEdit from '../edit';

/**
 * @name 待办管理
 */
const ToDoManage = () => {
  const location = useLocation();
  const table = useRef({
    queryFilter: {},
  });

  const [drawerFormVisible, setDrawerFormVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [editVisible, setEditVisible] = useState(false);
  const [query, setQuery] = useState({});

  /**
   * @name 跳转待办详情页面
   */
  const detailHandler = useCallback(({id}) => {
    setQuery({id});
    setDrawerFormVisible(true);
    setDetailVisible(true);
  }, []);

// 在组件内需要定义这两个方法
  const editHandler = useCallback(({id}) => {
    setQuery({id});
    setDrawerFormVisible(true);
    setEditVisible(true);
  }, []);

  const deleteHandler = (record) => {
    if (!record.id) return;
    serviceDeleteTodo(record)  // 调用删除接口（传递记录的 id）
      .then(() => {
        message.success('删除成功');  // 成功提示
        table.current.reloadAndRest();  // 刷新表格数据
      })
      .catch((error) => {
        message.error(`删除失败：${error.message}`);  // 错误提示
      });

  };
  // * 表格列配置
  const columns = useMemo(
    () => [
      {
        title: '待办ID',
        width: 200,
        fixed: 'left',
        dataIndex: 'id',
      },
      {
        title: '待办内容',
        width: 150,
        fixed: 'left',
        dataIndex: 'tasksContent',
      },
      {
        title: '来源应用',
        width: 150,
        fixed: 'left',
        dataIndex: 'sourceApplicationName',
      },
      {
        title: '处理人',
        width: 150,
        dataIndex: 'operatorName',
      },
      {
        title: '创建人工号',
        width: 150,
        dataIndex: 'creator',
      },
      {
        title: '创建人名称',
        width: 150,
        dataIndex: 'creatorName',
      },
      {
        title: '待办创建时间',
        width: 200,
        dataIndex: 'createTime',
      },
      {
        title: '计划完成时间',
        width: 300,
        dataIndex: 'expireTime',
      },
      {
        title: 'Task ID',
        width: 200,
        dataIndex: 'taskInstanceId',
      },
      {
        title: '跳转连接',
        width: 350,
        dataIndex: 'jumpConnection',
        ellipsis: true,
        hideInTable: true,
      },
      {
        title: '是否转办',
        width: 100,
        dataIndex: 'isTransfer',
        hideInTable: true,
        render(_) {
          return (
            {
              true: '是',
              false: '否',
            }[_] ?? ''
          );
        },
      },
      {
        title: '是否紧急',
        width: 100,
        dataIndex: 'isUrgent',
        hideInTable: true,
        render(_) {
          return (
            {
              true: '是',
              false: '否',
            }[_] ?? ''
          );
        },
      },
      {
        title: '自定义变量',
        width: 240,
        dataIndex: 'fieldArea',
        ellipsis: true,
        hideInTable: true,
        render(_, record) {
          try {
            const {fieldArea} = record;
            return JSON.stringify(fieldArea);
          } catch (error) {
            return '';
          }
        },
      },
      {
        title: '待办状态',
        width: 100,
        dataIndex: 'status',
        hideInTable: true,
      },
      {
        title: '操作',
        width: 200,
        fixed: 'right',
        dataIndex: 'action',
        render: (_, record) => (
          <>
            <Button type="link" size="small" onClick={() => detailHandler(record)}>
              详情
            </Button>
            <Divider type="vertical"/>
            <Button type="link" size="small" onClick={() => editHandler(record)}>
              编辑
            </Button>
            <Divider type="vertical"/>
            <Popconfirm
              placement="left"
              title={`确定删除此待办?`}
              onConfirm={() => {
                deleteHandler(record);
              }}
              okText="确定"
              cancelText="取消"
            >
              <a
                onClick={(e) => {
                  e.preventDefault();
                }}
              >
                删除
              </a>
            </Popconfirm>
          </>
        ),
      },
    ],
    [detailHandler],
  );

  /**
   * @name 表格请求数据
   */
  const request = useCallback(async (params) => {
    const collectParams = Object.assign({}, params, table.current.queryFilter ?? {});
    return serviceGetTodoList(collectParams);
  }, []);

  /**
   * @name 筛选表单提交事件
   * @param { Object } values 筛选表单最新值
   */
  const onSearch = async (values) => {
    const queryFilter = Object.assign({}, values);
    const {createTime = {}, expireTime = {}} = queryFilter;
    const {startTime, endTime} = createTime;
    if (startTime) {
      const newCreateTimeStart = moment(startTime).format('YYYY-MM-DD');
      queryFilter.createTime.startTime = newCreateTimeStart;
    }
    if (endTime) {
      const newCreateTimeEnd = moment(endTime).format('YYYY-MM-DD');
      queryFilter.createTime.endTime = newCreateTimeEnd;
    }
    if (startTime && endTime && moment(startTime) > moment(endTime)) {
      message.warn('生成时间结束时间需要大于开始时间!');
      return null;
    }
    const {startTime: expireStartTime = null, endTime: expireEndTime = null} = expireTime;
    if (expireStartTime) {
      const newCreateTimeStart = moment(expireStartTime).format('YYYY-MM-DD');
      queryFilter.expireTime.startTime = newCreateTimeStart;
    }
    if (expireEndTime) {
      const newCreateTimeEnd = moment(expireEndTime).format('YYYY-MM-DD');
      queryFilter.expireTime.endTime = newCreateTimeEnd;
    }
    if (expireStartTime && expireEndTime && moment(expireStartTime) > moment(expireEndTime)) {
      message.warn('计划完成时间结束时间需要大于开始时间!');
      return null;
    }
    table.current.queryFilter = queryFilter;
    table.current.reloadAndRest();
    return null;
  };

  /**
   * @name 详情弹层关闭
   */
  const onClose = useCallback(() => {
    setDrawerFormVisible(false);
    setDetailVisible(false);
    setEditVisible(false);
    setQuery({});
  }, []);

  /**
   * @name 详情弹层底部渲染
   */
  const drawerFooter = useMemo(
    () => (
      <div style={{display: 'flex', justifyContent: 'flex-end'}}>
        <Button onClick={onClose} type="primary">
          关闭
        </Button>
      </div>
    ),
    [],
  );

  useMount(() => {
    const {query = {}} = location;
    const {openDetailId} = query;
    if (openDetailId) {
      setQuery({id: openDetailId});
      setDrawerFormVisible(true);
    }
  });

  return (
    <div>
      <TableQueryForm onSearch={onSearch}/>
      <div style={{background: '#fff', marginBottom: 10, padding: 10}}>
        <CustomerTable ref={table} columns={columns} request={request} columnControl/>
      </div>
      <Drawer
        title="详情"
        width={600}
        visible={drawerFormVisible}
        footer={drawerFooter}
        onClose={onClose}
      >
        {detailVisible && (<ToDoDetail query={query}/>)}
        {editVisible && (<ToDoEdit query={query}/>)}
      </Drawer>
    </div>
  );
};

ToDoManage.propTypes = {};
ToDoManage.defaultProps = {};

export default React.memo(ToDoManage);
